package dispatch

import (
	"github.com/prometheus/client_golang/prometheus"
)

// MetricDispatchDurationObserve 记录派单决策耗时
var (
	metricDispatchDuration = prometheus.NewHistogramVec(
		prometheus.HistogramOpts{
			Namespace: "ride_hailing",
			Subsystem: "dispatch",
			Name:      "decision_duration_seconds",
			Help:      "派单决策耗时(秒)",
			Buckets:   prometheus.DefBuckets,
		},
		[]string{"city"},
	)
	// 派单决策结果
	metricDispatchResult = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Namespace: "ride_hailing",
			Subsystem: "dispatch",
			Name:      "decision_total",
			Help:      "派单决策总次数, 按结果分类",
		},
		[]string{"city", "result"},
	)
)

func init() {
	prometheus.MustRegister(metricDispatchDuration)
	prometheus.MustRegister(metricDispatchResult)
}

func MetricDispatchDurationObserve(seconds float64, cityId uint32) {
	metricDispatchDuration.WithLabelValues(itoa(cityId)).Observe(seconds)
}

func MetricDispatchResultInc(cityId uint32, result string) {
	metricDispatchResult.WithLabelValues(itoa(cityId), result).Inc()
}

func itoa(u uint32) string {
	if u == 0 {
		return "0"
	}
	b := make([]byte, 0, 10)
	for u > 0 {
		b = append(b, byte('0'+u%10))
		u /= 10
	}
	for i, j := 0, len(b)-1; i < j; i, j = i+1, j-1 {
		b[i], b[j] = b[j], b[i]
	}
	return string(b)
}
